<?php
namespace common\services;

use common\base\BaseActiveRecord;
use common\helpers\TStringHelper;
use common\models\Exhibition;
use common\models\ExhibitionHall;
use common\models\ExhibitionHallPicture;
use common\models\Region;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;

class ExhibitionHallServices extends ExhibitionHall
{

    /**
     * 展馆
     * @param $params
     * @return array
     */
    public function search($params){
        $model = ExhibitionHall::find(false);
        $model->orderBy('id desc');

        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['region_id']) && $params['region_id'] != '') {
            $model->andFilterWhere(['=', 'region_id', $params['region_id']]);
        }
        if (isset($params['recommend']) && $params['recommend'] != '') {
            $model->andFilterWhere(['=', 'recommend', $params['recommend']]);
        }
        if (isset($params['status']) && $params['status'] != '') {
            $model->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or', ['like', 'title', $params['keywords']], ['like', 'introduce', $params['keywords']], ['like', 'address', $params['keywords']]]);
        }

        if (isset($params['order'])) {
            $model->orderBy($params['order']);
        }

        //$sql = $model->createCommand()->getRawSql();

        return $dataProvider;
    }

    /**
     * @return array
     */
    public static function getHallDropdownList(){
        $model = ExhibitionHall::find(false);
        $result = $model->andFilterWhere(['=', 'status', ExhibitionHall::STATUS_FLAG_NORMAL])
            ->orderBy('order desc, id desc')
            ->select('id,title')
            ->asArray()
            ->all();
        $data = array();
        if (!empty($result)) {
            foreach ($result as $val){
                $data[$val['id']] = $val['title'];
            }
        }
        return $data;
    }

    /**
     * 获取推荐展馆
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getSearchArray($params = array()) {
        $model = ExhibitionHall::find(false);
        $model->andFilterWhere(['=', 'status', ExhibitionHall::STATUS_FLAG_NORMAL]);
        if (isset($params['order'])) {
            //$model->andFilterWhere(['=', 'recommend', $params['recommend']]);
            $model->orderBy($params['order']);
        }else{
            $model->orderBy('order desc, id desc');
        }

            $model->select('id, title, hotpic, area, address')
            ->asArray();
        if ($params['limit']) {
            $model->limit($params['limit']);
        }
        $res = $model->all();
        return $res;
    }

    /**
     * 获取城市列表
     * 1、根据展馆查询
     * 2、根据后台设置热门查询
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getHallCity($limit = 27) {
        $model = ExhibitionHall::find(false)
            ->andFilterWhere(['=', 'status', ExhibitionHall::STATUS_FLAG_NORMAL])
            ->groupBy('region_id')
            ->asArray()
            ->select('id,region_id');

        $res = $model->all();

        $regionArray = [];
        if (!empty($res)) {
            $regionArray = ArrayHelper::map($res, 'id', 'region_id');
            $regionArray = array_values($regionArray);
        }
        $region = Region::find(false)->andFilterWhere(['=', 'status', Region::STATUS_FLAG_NORMAL]);
        if (!empty($regionArray)) {
            $region->andFilterWhere(['in', 'id', $regionArray])->orderBy('order desc, id asc');
        }else{
            $limit = $limit > 0 ? $limit : 27;
            $region->orderBy('is_hot desc,order desc, id asc');
        }
        $region->asArray()->select('id,name');
        if ($limit > 0) {
            $region->limit($limit);
        }

        return $region->all();
    }

    /**
     * 获取展馆展会
     * @param $hall_id
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getHallExhibition($hall_id, $limit = 0, $order = '') {
        $model = Exhibition::find(false);
        $model->andFilterWhere(['=', 'status', Exhibition::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['=', 'hall_id', $hall_id]);

        if ( $limit > 0) {
            $model->limit($limit);
        }

        if (!empty($order)) {
            $model->orderBy($order);
        }

        $res = $model->select('id, title, logo, starttime, endtime')->asArray()->all();
        if (!empty($res)) {
            foreach ($res as $key => &$val) {
                $starttime = $val['starttime'];
                $endtime = $val['endtime'];
                if (date('Y', $starttime) == date('Y', $endtime)) {
                    $val['show_start'] = date('m-d', $starttime);
                    $val['show_end'] = date('m-d', $endtime);
                } else {
                    $val['show_start'] = date('m-d', $starttime);
                    $val['show_end'] = date('m-d', $endtime);
                }
            }
        }

        return $res;
    }

    public function getDetail($id) {
        $model = ExhibitionHall::findOne($id);

        if (empty($model)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        $data = array(
            'model' => $model,
        );
        //查询当年展会计划
        $exhibitionService = new ExhibitionServices();
        $data['list'] = $exhibitionService->getHallExhibitionByHallId($model->id);

        $pictureService = new ExhibitionHallPictureServices();
        //展馆图片
        $data['picture'] = $pictureService->getExhibitionHallPictureByHallId($model->id, ExhibitionHallPicture::HALL_PICTURE_TYPE_PHOTO);
        //展馆视频
        $data['video'] = $pictureService->getExhibitionHallPictureByHallId($model->id, ExhibitionHallPicture::HALL_PICTURE_TYPE_VIDEO);

        return $data;
    }

    /**
     * 根据地区ID获取展馆列表
     * @param $region_id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getRegionHall($region_id = '', $limit = 0) {
        $model = ExhibitionHall::find(false);
        $model->andFilterWhere(['=', 'status', ExhibitionHall::STATUS_FLAG_NORMAL]);
        if (!empty($region_id)) {
            //判断是否有子类
            $regionService = new RegionServices();
            $child = $regionService->getRegion($region_id);
            if (!empty($child)) {
                $childId = ArrayHelper::map($child, 'id', 'id');
                $childId = array_values($childId);
                array_push($childId, $region_id);
                $model->andFilterWhere(['in', 'region_id', $childId]);
            } else {
                $model->andFilterWhere(['=', 'region_id', $region_id]);
            }
        }
        $model->asArray()
            ->select('id, title, litpic, region_id, introduce')
            ->orderBy('recommend desc, order desc, id desc');

        if ($limit > 0) {
            $model->limit($limit);
        }

        $list = $model->all();

        if (!empty($list)) {
            $exhibitionService = new ExhibitionServices();
            $time = time();
            foreach ($list as &$value) {
                $exhibition = $exhibitionService->getNearExhibitionByHallId($value['id']);
                if (!empty($exhibition[0])) {
                    if ($exhibition[0]['starttime'] < $time && $exhibition[0]['endtime'] > $time) {
                        $value['show_start'] = \Yii::t('frontend', 'exhibition_being');//正在开展
                    }else {
                        $starttime = $exhibition[0]['starttime'];
                        if ($starttime > $time) {
                            $diff = ($starttime - $time) / 86400;
                            //开展于当天时间内
                            if ($starttime > strtotime(date('Y-m-d 00:00:00')) && $starttime < strtotime(date('Y-m-d 23:59:59'))) {
                                $value['show_start'] = \Yii::t('frontend', 'exhibition_being');//正在开展
                            } else {
                                $diff = ceil($diff);
                                //距离开展还剩<i>{day}</i>天
                                $value['show_start'] = \Yii::t('frontend', 'exhibition_uncarried_{day}', ['day' => $diff]);
                            }
                        } else {
                            $diff = ($time - $exhibition[0]['endtime']) / 86400;
                            $diff = ceil($diff);
                            if ($diff > 99) {
                                $diff = ceil($diff / 30);
                                //上次开展于<i>{day}</i>月前
                                $value['show_start'] = \Yii::t('frontend', 'exhibition_end_{month}', ['month' => $diff]);
                            }else{
                                //上次开展于<i>{day}</i>天前
                                $value['show_start'] = \Yii::t('frontend', 'exhibition_end_{day}', ['day' => $diff]);
                            }
                        }
                    }
                }
                $value['city'] = Region::getRegionName($value['region_id']);
            }
        }

        return $list;
    }

    /**
     * 根据展馆标题查询展馆信息
     * @param $title
     * @return array|bool|null
     */
    public function getHallInfoByTitle($title) {
        if (empty($title)) return false;
        $model = ExhibitionHall::findOne(['status' => ExhibitionHall::STATUS_FLAG_NORMAL, 'title' => $title]);

        return $model ? $model->toArray() : null;
    }

}
